package leetcode.ElementaryAlgorithm._1;

import javax.management.modelmbean.RequiredModelMBean;
import java.util.HashMap;
import java.util.Map;

/**
 * @author gh
 * @create 2021-08-19 14:25
 */
public class delSortedArrayReaptData {

    public static void main(String[] args) {
        int[] nums = {1, 1, 2};
//        int i = new delSortedArrayReaptData().removeDuplicates(nums);
//        System.out.println(i);
//
//        int i2 = new delSortedArrayReaptData().removeDuplicates2(nums);
//        System.out.println(i2);
        int[] nums2 = {2, 0, 0, 1, 1, 2};
        System.out.println(new delSortedArrayReaptData().removeDuplicates3(nums2));
        ;
    }

    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int p = 0;
        int q = 1;
        while (q < nums.length) {
            if (nums[p] != nums[q]) {
                nums[p + 1] = nums[q];
                p++;
            }
            q++;
        }
        for (int i = 0; i < nums.length; i++) {
            System.out.println(nums[i]);
        }
        return p + 1;
    }

    //双指针解决
    public int removeDuplicates2(int[] A) {
        //边界条件判断
        if (A == null || A.length == 0) {
            return 0;
        }
        int left = 0;
        for (int right = 1; right < A.length; right++)
        //如果左指针和右指针指向的值一样，说明有重复的，
        //这个时候，左指针不动，右指针继续往右移。如果他俩
        //指向的值不一样就把右指针指向的值往前挪
        {
            if (A[left] != A[right]) {
                A[++left] = A[right];
            }
        }
        for (int i = 0; i < A.length; i++) {
            System.out.println(A[i]);
        }
        return ++left;
    }

    public int removeDuplicates3(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        Map<Integer, Integer> map = new HashMap<>();
        int temp1 = -1;
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], i);
                if (i > 1) {
                    nums[temp1 + 1] = nums[i];
                }
                temp1++;
            }
        }
        return ++temp1;
    }

    public int removeDuplicates4(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        Map<Integer, Integer> map = new HashMap<>();
        int temp1 = 0;
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], i);
                if (i != 0) {
                    temp1++;
                    nums[temp1] = nums[i];
                }
            }
        }
        return ++temp1;
    }
}
